﻿using System;
using System.Web.Security;
using FFIV.Lib.Utilities;
using FFIV.Lib.WebExtension;

public partial class Views_Users_LoginUser : System.Web.UI.UserControl
{
	public void Page_Load()
	{
		LoadLoginState();

		RegisteEvents();
	}

	public void RegisteEvents()
	{
		btn_Login.Click += btn_Login_Click;
		btn_LogOut.Click += btn_LogOut_Click;
	}

	private void LoadLoginState()
	{
		Guid? userId = UsersUtility.GetCurrentUserId();
		if (userId != null && Membership.GetUser(userId.Value) != null)
		{
			LoginPresents();
		}
		else
		{
			LogoutPresents();
		}
	}

	private void btn_Login_Click(object sender, EventArgs e)
	{
		bool isLoginSucess = UsersUtility.LogIn(tb_UserName.Text, tb_Password.Text);

		if (isLoginSucess)
		{
			LoginPresents();
		}
		else
		{
			ErrorPresents();
		}

		RefreshCurrentPage();
	}

	private void btn_LogOut_Click(object sender, EventArgs e)
	{
		UsersUtility.LogOut();

		LogoutPresents();

		RefreshCurrentPage();
	}

	private void LoginPresents()
	{
		WelcomeDialg.Visible = true;
		LoginDialg.Visible = false;

		lbl_Welcome.Text = string.Format("{0}  您好！", UsersUtility.GetCurrentUserName());
	}

	private void LogoutPresents()
	{
		WelcomeDialg.Visible = false;
		LoginDialg.Visible = true;

		lbl_ErrorMessage.Text = "";
	}

	private void ErrorPresents()
	{
		WelcomeDialg.Visible = false;
		LoginDialg.Visible = true;

		lbl_ErrorMessage.Text = "用户名或密码错";
	}

	private void RefreshCurrentPage()
	{
		if (Page is FFWebPageBase)
		{
			((FFWebPageBase)Page).CheckPremission();
			((FFWebPageBase)Page).ShowMessage();
		}
	}

}
